package cn.kgc.crowd1048.fundingadmin.service.impl;

import cn.kgc.crowd1048.fundingadmin.common.CrowdFundingUtils;
import cn.kgc.crowd1048.fundingadmin.pojo.Admin;
import cn.kgc.crowd1048.fundingadmin.pojo.Auth;
import cn.kgc.crowd1048.fundingadmin.pojo.Role;
import cn.kgc.crowd1048.fundingadmin.service.AdminService;
import cn.kgc.crowd1048.fundingadmin.service.AuthService;
import cn.kgc.crowd1048.fundingadmin.service.RoleService;
import cn.kgc.crowd1048.fundingadmin.vo.SecurityAdmin;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class CrowdUserDetailsService implements UserDetailsService {

    @Resource
    AdminService adminService;
    @Resource
    RoleService roleService;

    @Resource
    AuthService authService;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        QueryWrapper<Admin> wrapper=new QueryWrapper<>();
        wrapper.eq("login_acct",s);
        Admin admin = adminService.getOne(wrapper);
        if(admin!=null){
            //封装角色和权限的集合
            List<GrantedAuthority> authorityList=new ArrayList<>();
            //获取角色
            List<Role> assignedRoleList = roleService.getAssignedRoleList(admin.getId());
            //获取角色编号,查询权限时使用
            List<Integer> roleIds=new ArrayList<>();
            //封装角色
            for (Role role:assignedRoleList){
                String roleName="ROLE_"+role.getName();
                authorityList.add(new SimpleGrantedAuthority(roleName));
                roleIds.add(role.getId());
            }
            //封装权限
            List<Auth> auths = authService.selectByRoleIds(roleIds);
            for (Auth auth : auths) {
                if (CrowdFundingUtils.stringEffective(auth.getName())==false){
                    continue;
                }
                authorityList.add(new SimpleGrantedAuthority(auth.getName()));
            }
            SecurityAdmin securityAdmin = new SecurityAdmin(admin, authorityList);
            return securityAdmin;

        }


        //封装角色和权限信息
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList("ROLE_studnet", "ROLE_teacher");
        return new User(admin.getUserName(),admin.getUserPswd(),authorityList);


    }
}

